package com.mhf.service.impl;

import com.mhf.domain.JSONResult;
import com.mhf.domain.Movie;
import com.mhf.domain.MovieUser;
import com.mhf.mapper.MovieMapper;
import com.mhf.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class MovieServiceImpl implements MovieService {
    @Autowired
    private MovieMapper movieMapper;
    @Override
    public Movie getById(Long id) {
        return movieMapper.getById(id);
    }

    @Override

    public void buyMovie(MovieUser movieUser) {

        //1.通过电影id获取电影信息
        Long moveId = movieUser.getMovieTicketId();
        Movie movie = movieMapper.getById(moveId);
        //2.判断库存
        Long stock = movie.getStock();
        Long count = movieUser.getCount();
        Long newStock = stock-count;
        if (newStock<=0){
            throw new RuntimeException("库存不足");
        }
        //3.保存到表中
        movie.setStock(newStock);
        //修改电影信息
        movieMapper.update(movie);
        //修改中间表
        movieMapper.addTicketUser(movieUser);
/*        //随机获取一个数作为电影id
        double movieId1 = Math.random() * 10;
        String strId = String.valueOf(movieId1);
        Long mid = Long.valueOf(strId);
        movieUser.setMovieTicketId(20L);
        movieUser.setCount(1L);
        JSONResult jsonResult = new JSONResult();
        jsonResult.setResultObj(movieUser);*/
    }

    @Override
    public MovieUser getByUserMovie(Long userId) {

        return movieMapper.getByUserMovie(userId);
    }
}
